import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useTeamChatStore } from './teamChat'
import { useAuthStore } from './auth'
import { useEncryptionStore } from './encryption'
import { teamApi } from '@/api/team'
import { getTeamMessages } from '@/api/teamMessage'

/**
 * 通知数据类型
 */
export interface NotificationItem {
  id: string
  teamId: number
  teamName: string
  teamAvatar?: string
  senderId: number
  senderName: string
  messageType: 'text' | 'image' | 'file'
  content: string
  fileName?: string
  timestamp: number
  isRead: boolean
  unreadCount: number
  // 加密相关字段
  isEncrypted?: boolean
  iv?: string
  encryptionAlgorithm?: string
  keyVersion?: number
  // 解密后的内容（用于显示）
  decryptedContent?: string
  decryptedFileName?: string
}

/**
 * 全局通知状态管理
 */
export const useNotificationStore = defineStore('notification', () => {
  // 状态
  const notifications = ref<NotificationItem[]>([])
  const isViewed = ref(false) // 是否已查看通知面板

  // 计算属性
  const totalUnreadCount = computed(() => {
    return notifications.value.reduce((total, notification) => {
      return total + (notification.isRead ? 0 : notification.unreadCount)
    }, 0)
  })

  const unreadNotifications = computed(() => {
    return notifications.value.filter(notification => !notification.isRead)
  })

  // 方法

  /**
   * 获取用户通知状态存储键
   */
  const getUserNotificationKey = (userId: number) => `notification_state_${userId}`

  /**
   * 获取用户通知状态
   */
  const getUserNotificationState = () => {
    const authStore = useAuthStore()
    if (!authStore.user?.id) return null

    const key = getUserNotificationKey(authStore.user.id)
    const stateStr = localStorage.getItem(key)

    if (!stateStr) return null

    try {
      return JSON.parse(stateStr)
    } catch (error) {
      console.warn('⚠️ 解析用户通知状态失败:', error)
      return null
    }
  }

  /**
   * 保存用户通知状态
   */
  const saveUserNotificationState = (state: {
    lastReadTime?: number
    clearedTime?: number
    readNotifications?: string[]
  }) => {
    const authStore = useAuthStore()
    if (!authStore.user?.id) return

    const key = getUserNotificationKey(authStore.user.id)
    const currentState = getUserNotificationState() || {}

    const newState = {
      ...currentState,
      ...state,
      updatedAt: Date.now()
    }

    localStorage.setItem(key, JSON.stringify(newState))
    console.log('💾 用户通知状态已保存:', newState)
  }

  /**
   * 加载离线期间的未读消息通知
   */
  const loadOfflineNotifications = async () => {
    try {
      console.log('📥 开始加载离线期间的未读消息...')

      // 获取用户通知状态
      const authStore = useAuthStore()
      const notificationState = getUserNotificationState()

      // 获取用户所有团队
      const teamsResponse = await teamApi.getMyTeams()
      console.log('📋 团队API响应:', teamsResponse)

      if (teamsResponse.code !== 200 || !teamsResponse.data) {
        console.warn('⚠️ 获取用户团队列表失败:', teamsResponse)
        return
      }

      const teams = teamsResponse.data
      console.log(`📋 用户共有 ${teams.length} 个团队:`, teams)

      // 获取关键时间戳
      const lastReadTime = notificationState?.lastReadTime || 0
      const clearedTime = notificationState?.clearedTime || 0
      const readNotifications = notificationState?.readNotifications || []

      // 为每个团队检查未读消息
      for (const team of teams) {
        try {
          // 获取团队的最新消息（第一页）
          const messagesResponse = await getTeamMessages(team.id, 0, 10)
          console.log(`📨 团队 ${team.name} 消息响应:`, messagesResponse)

          if (messagesResponse.code === 200 && messagesResponse.data?.messages) {
            const messages = messagesResponse.data.messages
            console.log(`📨 团队 ${team.name} 共有 ${messages.length} 条消息`)

            const unreadMessages = messages.filter(msg => {
              // 消息时间晚于最后已读时间和清空时间，且不是自己发送的
              const isAfterReadTime = msg.timestamp > lastReadTime
              const isAfterClearedTime = msg.timestamp > clearedTime
              const isNotSelfSent = msg.senderId !== authStore.user?.id
              const isNotRead = !readNotifications.includes(`${team.id}_${msg.id}`)

              // 修复逻辑：如果设置了全局已读时间且消息时间早于该时间，则视为已读
              // 如果设置了清空时间且消息时间早于该时间，则不显示
              const isGlobalRead = lastReadTime > 0 && msg.timestamp <= lastReadTime
              const isGlobalCleared = clearedTime > 0 && msg.timestamp <= clearedTime
              
              // 消息必须：1.不是自己发送的 2.没有被全局清空 3.没有被全局标记已读 4.不在单独已读列表中
              return isNotSelfSent && !isGlobalCleared && !isGlobalRead && isNotRead
            })

            if (unreadMessages.length > 0) {
              // 为这个团队创建一个汇总通知
              const latestMessage = unreadMessages[0]
              await addNotification({
                id: `offline_${team.id}_${Date.now()}`,
                teamId: team.id,
                senderId: latestMessage.senderId,
                senderName: latestMessage.senderName,
                messageType: latestMessage.messageType,
                content: latestMessage.content,
                fileName: latestMessage.fileName,
                timestamp: latestMessage.timestamp,
                isRead: false,
                unreadCount: unreadMessages.length,
                // 传递加密相关字段
                isEncrypted: latestMessage.isEncrypted,
                iv: latestMessage.iv,
                encryptionAlgorithm: latestMessage.encryptionAlgorithm,
                keyVersion: latestMessage.keyVersion
              })

              console.log(`📨 团队 ${team.name} 有 ${unreadMessages.length} 条未读消息`)
            }
          }
        } catch (error) {
          console.error(`获取团队 ${team.name} 消息失败:`, error)
        }
      }

      console.log('✅ 离线消息加载完成')
    } catch (error) {
      console.error('❌ 加载离线消息失败:', error)
    }
  }

  /**
   * 初始化通知系统
   */
  const init = async () => {
    console.log('🔔 通知系统初始化')

    // 先加载离线期间的未读消息
    await loadOfflineNotifications()

    // 监听团队消息
    const teamChatStore = useTeamChatStore()
    const authStore = useAuthStore()

    // 直接监听teamChatStore的Socket事件
    if (teamChatStore.teamSocketManager) {
      teamChatStore.teamSocketManager.on('new_team_message', async (message: any) => {
        console.log('🔔 收到新团队消息，准备生成通知:', message)

        // 只有不是自己发送的消息才添加通知
        if (message && message.senderId !== authStore.user?.id) {
          try {
            await addNotification({
              id: `${message.teamId}_${message.id}_${Date.now()}`,
              teamId: message.teamId,
              senderId: message.senderId,
              senderName: message.senderName,
              messageType: message.messageType,
              content: message.content,
              fileName: message.fileName,
              timestamp: message.timestamp,
              isRead: false,
              unreadCount: 1,
              // 传递加密相关字段
              isEncrypted: message.isEncrypted,
              iv: message.iv,
              encryptionAlgorithm: message.encryptionAlgorithm,
              keyVersion: message.keyVersion
            })
          } catch (error) {
            console.error('添加通知失败:', error)
          }
        }
      })
    } else {
      console.warn('⚠️ teamSocketManager未初始化，将延迟监听')
      // 延迟监听，等待Socket连接建立
      const setupDelayedListener = () => {
        setTimeout(() => {
          if (teamChatStore.teamSocketManager) {
            console.log('✅ 延迟监听设置成功')
            teamChatStore.teamSocketManager.on('new_team_message', async (message: any) => {
              console.log('🔔 收到新团队消息，准备生成通知:', message)

              if (message && message.senderId !== authStore.user?.id) {
                try {
                  await addNotification({
                    id: `${message.teamId}_${message.id}_${Date.now()}`,
                    teamId: message.teamId,
                    senderId: message.senderId,
                    senderName: message.senderName,
                    messageType: message.messageType,
                    content: message.content,
                    fileName: message.fileName,
                    timestamp: message.timestamp,
                    isRead: false,
                    unreadCount: 1
                  })
                } catch (error) {
                  console.error('添加通知失败:', error)
                }
              }
            })
          } else {
            console.warn('⚠️ 延迟监听失败，继续等待...')
            setupDelayedListener() // 递归重试
          }
        }, 2000)
      }
      setupDelayedListener()
    }
  }

  /**
   * 解密通知内容
   */
  const decryptNotificationContent = async (notification: NotificationItem): Promise<NotificationItem> => {
    // 如果消息未加密或已经解密过，直接返回
    if (!notification.isEncrypted || notification.decryptedContent) {
      return notification
    }

    try {
      const encryptionStore = useEncryptionStore()

      // 获取团队密钥（暂时使用当前密钥，后续可以优化支持版本）
      const teamKey = await encryptionStore.getTeamKey(notification.teamId)

      // 导入MessageEncryption
      const { MessageEncryption } = await import('@/utils/encryption/MessageEncryption')

      // 解密消息内容
      if (notification.content && notification.iv && notification.encryptionAlgorithm) {
        const encryptedData = {
          ciphertext: notification.content,
          iv: notification.iv,
          algorithm: notification.encryptionAlgorithm
        }
        notification.decryptedContent = await MessageEncryption.decryptMessage(encryptedData, teamKey)
      }

      // 解密文件名（如果有）
      if (notification.fileName && notification.messageType !== 'text' && notification.iv && notification.encryptionAlgorithm) {
        try {
          // 检查文件名是否看起来像Base64加密字符串
          if (notification.fileName.length > 20 && /^[A-Za-z0-9+/=]+$/.test(notification.fileName)) {
            const encryptedFileName = {
              ciphertext: notification.fileName,
              iv: notification.iv,
              algorithm: notification.encryptionAlgorithm
            }
            notification.decryptedFileName = await MessageEncryption.decryptMessage(encryptedFileName, teamKey)
          } else {
            notification.decryptedFileName = notification.fileName
          }
        } catch (error) {
          console.warn('⚠️ 通知文件名解密失败:', error)
          notification.decryptedFileName = notification.fileName
        }
      }

      console.log('✅ 通知内容解密成功:', notification.id)
    } catch (error) {
      console.warn('⚠️ 通知内容解密失败:', error)
      // 解密失败时使用原始内容
      notification.decryptedContent = notification.content
      notification.decryptedFileName = notification.fileName
    }

    return notification
  }

  /**
   * 添加通知
   */
  const addNotification = async (notification: Omit<NotificationItem, 'teamName' | 'teamAvatar'>) => {
    // 获取团队信息
    const teamName = await getTeamName(notification.teamId)
    const teamAvatar = await getTeamAvatar(notification.teamId)

    let fullNotification: NotificationItem = {
      ...notification,
      teamName,
      teamAvatar
    }

    // 如果消息是加密的，尝试解密
    if (fullNotification.isEncrypted) {
      fullNotification = await decryptNotificationContent(fullNotification)
    }

    // 检查是否已存在相同团队的通知
    const existingIndex = notifications.value.findIndex(
      item => item.teamId === fullNotification.teamId
    )

    if (existingIndex !== -1) {
      // 更新现有通知
      const existing = notifications.value[existingIndex]
      existing.content = fullNotification.content
      existing.messageType = fullNotification.messageType
      existing.fileName = fullNotification.fileName
      existing.timestamp = fullNotification.timestamp
      existing.senderName = fullNotification.senderName
      existing.senderId = fullNotification.senderId
      existing.unreadCount += 1
      existing.isRead = false

      // 移动到列表顶部
      notifications.value.splice(existingIndex, 1)
      notifications.value.unshift(existing)
    } else {
      // 添加新通知到列表顶部
      notifications.value.unshift(fullNotification)
    }

    // 限制通知数量（最多保留50条）
    if (notifications.value.length > 50) {
      notifications.value = notifications.value.slice(0, 50)
    }

    console.log(`🔔 新增通知: ${fullNotification.teamName} - ${fullNotification.senderName}`)
  }

  /**
   * 标记通知为已读
   */
  const markAsRead = (notificationId: string) => {
    const notification = notifications.value.find(item => item.id === notificationId)
    if (notification) {
      notification.isRead = true

      // 保存单个通知已读状态
      const currentState = getUserNotificationState() || {}
      const readNotifications = currentState.readNotifications || []

      // 修复 readKey 格式，与 loadOfflineNotifications 中的检查保持一致
      // 对于 offline 通知，需要提取真实的消息 ID
      let realMessageId = notificationId
      if (notificationId.startsWith('offline_')) {
        // offline_teamId_timestamp 格式，我们需要通过其他方式标记已读
        // 这里我们使用时间戳来标记该团队的所有消息为已读
        saveUserNotificationState({
          lastReadTime: notification.timestamp
        })
        console.log(`✅ 通知已读: ${notification.teamName} (通过时间戳标记)`)
        return
      }
      
      const readKey = `${notification.teamId}_${realMessageId}`
      if (!readNotifications.includes(readKey)) {
        readNotifications.push(readKey)

        saveUserNotificationState({
          readNotifications
        })
      }

      console.log(`✅ 通知已读: ${notification.teamName}`)
    }
  }

  /**
   * 标记所有通知为已读
   */
  const markAllAsRead = () => {
    // 更新内存状态
    notifications.value.forEach(notification => {
      notification.isRead = true
    })

    // 获取当前状态
    const currentState = getUserNotificationState() || {}
    const readNotifications = currentState.readNotifications || []
    
    // 将当前所有通知添加到已读列表
    notifications.value.forEach(notification => {
      const readKey = `${notification.teamId}_${notification.id.replace(/^offline_\d+_/, '').split('_').slice(0, 2).join('_')}`
      if (!readNotifications.includes(readKey)) {
        readNotifications.push(readKey)
      }
    })

    // 保存已读状态到localStorage
    saveUserNotificationState({
      lastReadTime: Date.now(),
      readNotifications
    })

    console.log('✅ 所有通知已标记为已读并持久化保存', { 
      lastReadTime: Date.now(), 
      readNotifications 
    })
  }

  /**
   * 标记通知面板为已查看
   */
  const markAsViewed = () => {
    isViewed.value = true
  }

  /**
   * 清空所有通知
   */
  const clearAll = () => {
    // 获取当前最新消息的时间戳，用作清空时间
    const latestTimestamp = notifications.value.length > 0 
      ? Math.max(...notifications.value.map(n => n.timestamp))
      : Date.now()
    
    // 清空内存状态
    notifications.value = []

    // 保存清空状态到localStorage
    // 使用最新消息时间戳作为清空时间，确保之前的消息不会再次加载
    saveUserNotificationState({
      clearedTime: latestTimestamp
    })

    console.log('🗑️ 所有通知已清空并持久化保存', { clearedTime: latestTimestamp })
  }

  /**
   * 移除指定通知
   */
  const removeNotification = (notificationId: string) => {
    const index = notifications.value.findIndex(item => item.id === notificationId)
    if (index !== -1) {
      const notification = notifications.value[index]
      notifications.value.splice(index, 1)
      console.log(`🗑️ 移除通知: ${notification.teamName}`)
    }
  }

  /**
   * 清理过期通知（7天前的通知）
   */
  const cleanupExpiredNotifications = () => {
    const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
    const beforeCount = notifications.value.length
    
    notifications.value = notifications.value.filter(
      notification => notification.timestamp > sevenDaysAgo
    )
    
    const removedCount = beforeCount - notifications.value.length
    if (removedCount > 0) {
      console.log(`🧹 清理了 ${removedCount} 条过期通知`)
    }
  }

  // 团队信息缓存
  const teamInfoCache = ref<Record<number, { name: string; avatar?: string }>>({})

  /**
   * 获取团队名称
   */
  const getTeamName = async (teamId: number): Promise<string> => {
    // 先从缓存获取
    if (teamInfoCache.value[teamId]) {
      return teamInfoCache.value[teamId].name
    }

    try {
      // 调用API获取团队信息
      const response = await teamApi.getTeamDetail(teamId)
      if (response.code === 200 && response.data) {
        const teamInfo = {
          name: response.data.name,
          avatar: response.data.teamAvatarUrl
        }

        // 缓存团队信息
        teamInfoCache.value[teamId] = teamInfo

        return teamInfo.name
      }
    } catch (error) {
      console.error(`获取团队${teamId}信息失败:`, error)
    }

    // 失败时返回默认名称
    return `团队 ${teamId}`
  }

  /**
   * 获取团队头像
   */
  const getTeamAvatar = async (teamId: number): Promise<string | undefined> => {
    // 先从缓存获取
    if (teamInfoCache.value[teamId]) {
      return teamInfoCache.value[teamId].avatar
    }

    try {
      // 调用API获取团队信息
      const response = await teamApi.getTeamDetail(teamId)
      if (response.code === 200 && response.data) {
        const teamInfo = {
          name: response.data.name,
          avatar: response.data.teamAvatarUrl
        }

        // 缓存团队信息
        teamInfoCache.value[teamId] = teamInfo

        return teamInfo.avatar
      }
    } catch (error) {
      console.error(`获取团队${teamId}头像失败:`, error)
    }

    return undefined
  }

  /**
   * 清理资源
   */
  const cleanup = () => {
    console.log('🧹 通知系统清理')

    // 清理Socket事件监听
    const teamChatStore = useTeamChatStore()
    if (teamChatStore.teamSocketManager) {
      teamChatStore.teamSocketManager.off('new_team_message')
    }

    // 清理定时器等资源
  }

  /**
   * 获取团队未读消息数
   */
  const getTeamUnreadCount = (teamId: number): number => {
    const notification = notifications.value.find(item => item.teamId === teamId)
    return notification && !notification.isRead ? notification.unreadCount : 0
  }

  /**
   * 清除团队通知
   */
  const clearTeamNotifications = (teamId: number) => {
    notifications.value = notifications.value.filter(item => item.teamId !== teamId)
    console.log(`🗑️ 清除团队 ${teamId} 的所有通知`)
  }

  /**
   * 更新团队信息
   */
  const updateTeamInfo = (teamId: number, teamName: string, teamAvatar?: string) => {
    notifications.value.forEach(notification => {
      if (notification.teamId === teamId) {
        notification.teamName = teamName
        if (teamAvatar) {
          notification.teamAvatar = teamAvatar
        }
      }
    })
  }

  // 定期清理过期通知（每小时执行一次）
  setInterval(cleanupExpiredNotifications, 60 * 60 * 1000)

  return {
    // 状态
    notifications,
    isViewed,
    totalUnreadCount,
    unreadNotifications,

    // 方法
    init,
    cleanup,
    addNotification,
    decryptNotificationContent,
    markAsRead,
    markAllAsRead,
    markAsViewed,
    clearAll,
    removeNotification,
    cleanupExpiredNotifications,
    getTeamUnreadCount,
    clearTeamNotifications,
    updateTeamInfo,
    getTeamName,
    getTeamAvatar,
    teamInfoCache,

    // 新增的状态管理方法
    getUserNotificationState,
    saveUserNotificationState
  }
})
